package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class LocalStopOrRecoverTypeHandler extends AbstractAttrHandler {
    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private OperateInstAttrService operateInstAttrService;

    private static final String NORMAL_STOP_ATTR_ID = "20210305901"; // 普通停机
    private static final String SPECIAL_STOP_ATTR_ID = "20001451047001"; // 特殊停机

    @Override
    public void init(CommonAttrVO commonAttr) {

    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        KiteAttr attr = querySceneInstService.getCommonAttr(sceneInstId, fieldName);
        // 值不变（公共属性模块处理类触发）,不再跑联动逻辑
        if (KiteStringUtils.isNotEmpty(value) && value.equals(attr.getValue())) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        //类型单选框选中时清空其它值
        List<KiteAttr> kiteAttrs = querySceneInstService.listCommonAttrsByModuleId(sceneInstId, attr.getModuleId()).stream()
            .filter(kiteAttr -> !fieldName.equals(kiteAttr.getFieldName())).collect(Collectors.toList());
        IOperateSceneCommonService operateSceneCommonService = SpringUtil.getBean(IOperateSceneCommonService.class);
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String postProvinceNbr = sceneInst.getProvinceNbr();
        // 湖南 停机和销户止租方式默认为“手动止租”，可修改
        if (LocalKeyConsts.PROVINCE_HUNAN.equals(postProvinceNbr)) {
            kiteAttrs.forEach(kiteAttr -> {
                // 止租方式不清空，止租时间默认隐藏
                if (!LocalKeyConsts.STOP_RENT_WAY.equals(kiteAttr.getFieldName())) {
                    kiteAttr.setValue(null);
                    kiteAttr.setValueDesc(null);
                }
                kiteAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_D);
                if (LocalKeyConsts.STOP_RENT_TIME.equals(kiteAttr.getFieldName())) {
                    kiteAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_E);
                }
                operateSceneCommonService.setCommonAttr(sceneInstId, kiteAttr);
            });
        } else if (LocalKeyConsts.PROVINCE_SHANGHAI.equals(postProvinceNbr)) {
            kiteAttrs.forEach(kiteAttr -> {
                // 止租方式不清空
                if (!KiteStringUtils.equalsAny(kiteAttr.getFieldName(), LocalKeyConsts.STOP_RENT_TIME, LocalKeyConsts.STOP_RENT_WAY, LocalKeyConsts.START_RENT_WAY)) {
                    kiteAttr.setValue(null);
                    kiteAttr.setValueDesc(null);
                }
                kiteAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_D);
                operateSceneCommonService.setCommonAttr(sceneInstId, kiteAttr);
            });
        } else {
            kiteAttrs.forEach(kiteAttr -> {
                if (KeyConsts.IFTRUE_T.equals(kiteAttr.getIsEdit())) {
                    kiteAttr.setValue(null);
                    kiteAttr.setValueDesc(null);
                }
                kiteAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_D);
                operateSceneCommonService.setCommonAttr(sceneInstId, kiteAttr);
            });
        }
        // 切换停机类型时，普通停机和特殊停机的停机原因下拉值不一样
        KiteAttr stopReasonAttr = kiteAttrs.stream().filter(attr1 -> (LocalKeyConsts.STOP_REASON.equals(attr1.getFieldName()))).findFirst().orElse(null);
        if (Objects.nonNull(stopReasonAttr)) {
            if (KiteStringUtils.equals(value, LocalServiceOfferConsts.SERVICE_OFFER_STOP)) {
                // 普通停机
                List<AttrValue> attrValues = AttrValueCache.get(NORMAL_STOP_ATTR_ID);
                stopReasonAttr.setValue(null);
                stopReasonAttr.setValueDesc(null);
                stopReasonAttr.setAttrValues(KiteBeanUtils.copyPropsForList(attrValues, KiteAttrValue.class));
            } else if (KiteStringUtils.equals(value, LocalServiceOfferConsts.SERVICE_OFFER_SPECIAL_STOP)) {
                // 特殊停机
                List<AttrValue> attrValues = AttrValueCache.get(SPECIAL_STOP_ATTR_ID);
                stopReasonAttr.setValue(null);
                stopReasonAttr.setValueDesc(null);
                stopReasonAttr.setAttrValues(KiteBeanUtils.copyPropsForList(attrValues, KiteAttrValue.class));
            }
            operateSceneCommonService.setCommonAttr(sceneInstId, stopReasonAttr);
        }
        // 停机保号资费
        this.dealShutDownAdditionalOffer(sceneInstId, value);

        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    private void dealShutDownAdditionalOffer(String sceneInstId, String value) {
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);

        List<KiteOfferInst> kiteOfferInsts = querySceneInstService.listAdditionalOfferInstsFromOfferInst(sceneInst.getCustId(), sceneInst.getRootInstId())
            .stream().filter(kiteOfferInst -> !KiteStringUtils.equalsAny(kiteOfferInst.getActionType().name(), ActionType.D.name(), ActionType.X.name()))
            .filter(kiteOfferInst -> {
                Map<String, Object> offerMap = Optional.ofNullable(OfferCache.get(kiteOfferInst.getOfferId())).map(Offer::getOfferMap).orElse(null);
                return LocalKeyConsts.FEE_PAY_TYPE_SHUTDOWN_NUMBER.equals(KiteMapUtils.getString(offerMap, "payType"));
            }).collect(Collectors.toList());

        KiteInst kiteInst = querySceneInstService.getKiteInst(sceneInst.getCustId(), sceneInst.getRootInstType(), sceneInst.getRootInstId());
        List<DcPublic> list = DcPublicCache.get("20210719001");
        // 是否五大双线落地方产品，无停机保号费，不显示资费服务模块
        boolean flag = (list != null) && list.stream().anyMatch(dcPublic -> KiteStringUtils.isEqual(kiteInst.getSpecId(), dcPublic.getCodeb()));
        if (flag) {
            kiteOfferInsts.forEach(kiteOfferInst -> operateSceneInstService.deleteAdditionalOfferInst(sceneInstId, kiteOfferInst.getOfferInstId()));
            return;
        }
        
        // 选中特殊停机时,把添加的停机保号费删除
        if ("1047".equals(value)) {
            kiteOfferInsts.forEach(kiteOfferInst -> operateSceneInstService.deleteAdditionalOfferInst(sceneInstId, kiteOfferInst.getOfferInstId()));
        }
        // 选中复机类型时,将停机保号费的失效时间设置为当天
        if (KiteStringUtils.equalsAny(value, "1004", "1048")) {
            kiteOfferInsts.forEach(kiteOfferInst -> {
                String currDate = DateFormatUtils.formatDate(KiteDateUtils.getEndOfDay(), DateFormatUtils.DATE_TIME_FORMAT);
                // 如果生效时间比当前时间要晚，则取生效时间，如果生效时间为空则默认当天
                String startDate = Optional.ofNullable(kiteOfferInst.getAttr(LocalKeyConsts.STARTING_DATE_FIELD_NAME)).map(KiteAttr::getValue).orElse(currDate);
                if (DateFormatUtils.compareDate(startDate, currDate, DateFormatUtils.DATE_TIME_FORMAT) > 0) {
                    operateInstAttrService.setAttrValue(kiteOfferInst, LocalKeyConsts.END_DATE_FIELD_NAME, startDate, sceneInstId, null);
                } else {
                    operateInstAttrService.setAttrValue(kiteOfferInst, LocalKeyConsts.END_DATE_FIELD_NAME, currDate, sceneInstId, null);
                }
            });
        }
    }
}
